package com.bdi.mqtt_broker.utils;

import com.bdi.mqtt_broker.config.BrokerConfig;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;

/**
 * @author WangNing yogehaoren@gmial.com <br>
 * @since 1.0
 */
@Component
public class JedisConnection {

    private static JedisPool jedisPool = null;

    @Autowired
    BrokerConfig brokerConfig;

    @PostConstruct
    public void initJedisConnection() throws Exception{

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(brokerConfig.getRedisMaxActive());//最大连接数
        config.setMaxIdle(brokerConfig.getRedisMaxIdle());//最大空闲连接数
        config.setMaxWaitMillis(brokerConfig.getRedisMaxWait());//获取可用连接的最大等待时间
        jedisPool = new JedisPool(config, brokerConfig.getRedisHost(),
                brokerConfig.getRedisPort(), brokerConfig.getRedisDatabase());
    }

    public Jedis getJedis(){

        Jedis jedis = jedisPool.getResource();


        if(brokerConfig.getRedisPassword()!=null&&!"".equals(brokerConfig.getRedisPassword())){
            jedis.auth(brokerConfig.getRedisPassword());
        }
        return jedis;

    }

}
